package com.hh.service.service.impl.im;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.hh.common.constants.ImConstants;
import com.hh.common.model.im.ImGroup;
import com.hh.common.model.im.ImRegisterFail;
import com.hh.common.model.user.User;
import com.hh.common.response.im.UserSigResponse;
import com.hh.common.utils.HhUtil;
import com.hh.common.utils.RandomCodeUtils;
import com.hh.common.utils.RestTemplateUtil;
import com.hh.common.vo.im.CommonResultVo;
import com.hh.service.dao.im.ImGroupOwnerAccountDao;
import com.hh.service.service.SystemAttachmentService;
import com.hh.service.service.UserService;
import com.hh.service.service.im.ImGroupService;
import com.hh.service.service.im.ImUserService;
import com.hh.service.service.user.ImRegisterFailService;
import com.tencentyun.TLSSigAPIv2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class ImUserServiceImpl extends BaseImService implements ImUserService {

    @Autowired
    private UserService userService;

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    @Autowired
    private ImRegisterFailService imRegisterFailService;

    @Autowired
    private SystemAttachmentService systemAttachmentService;

    @Autowired
    private ImGroupService imGroupService;

    @Resource
    private ImGroupOwnerAccountDao imGroupOwnerAccountDao;

    /**
     * 生成UserSig
     * @return
     */
    @Override
    public UserSigResponse generateUserSig() {
        User user = userService.getInfoException();
        UserSigResponse userSigResponse = new UserSigResponse();
        TLSSigAPIv2 tlsSigAPIv2 = new TLSSigAPIv2(getSdkAppId(), getSecretKey());
        String sig = tlsSigAPIv2.genUserSig(user.getImUid(), getExpire());
        userSigResponse.setUserSig(sig);
        userSigResponse.setExpire(String.valueOf(getExpire()));
        return userSigResponse;
    }

    /**
     * 注册Im账号
     * @param imUserId
     */
    @Override
    public boolean registerImAccount(String imUserId,String avatar,String nickname) {
        String avatarUrl = systemAttachmentService.prefixImage(avatar);
        String userSig = getAdminUserSig(getIdentifier());
        Integer ranDom = HhUtil.randomCount(11111111, 99999999);
        String url = String.format(ImConstants.ACCOUNT_IMPORT_URL,getSdkAppId(),getIdentifier(),userSig,ranDom);
        Map<String,Object> map = new HashMap<>();
        map.put("UserID",imUserId);
        map.put("Nick",nickname);
        map.put("FaceUrl",avatarUrl);
        String s = restTemplateUtil.postMapData(url, map);
        CommonResultVo result = JSONObject.parseObject(s, CommonResultVo.class);
        if("FAIL".equals(result.getActionStatus())){
            log.error("注册失败"+result.getErrorInfo());
            //记录到数据库
            ImRegisterFail imRegisterFail = new ImRegisterFail();
            imRegisterFail.setImId(imUserId);
            imRegisterFail.setFailCause(result.getErrorInfo());
            imRegisterFailService.insert(imRegisterFail);
            return true;
        }else {
            //自动加群
            String groupId;
            //获取群
            ImGroup imGroup = imGroupService.getGroupOneNotFull();
            if(ObjectUtil.isNull(imGroup)){
                //没有获取到群，则自动创建群
                groupId = imGroupService.createGroup();
            }else {
                groupId = imGroup.getGroupId();
            }
            if(StrUtil.isNotBlank(groupId)){
                //把该用户添加到群中
                imGroupService.addGroupMember(imUserId,groupId);
                return true;
            }else {
                log.error("创建群失败，不能获取群groupId");
                //创建群失败，不能获取群groupId
                return false;
            }
        }
    }

    @Override
    public Boolean registerImUser() {
        String imUserId = RandomCodeUtils.generateShortUuid();
        String userSig = getAdminUserSig(getIdentifier());
        Integer ranDom = HhUtil.randomCount(11111111, 99999999);
        String url = String.format(ImConstants.ACCOUNT_IMPORT_URL,getSdkAppId(),getIdentifier(),userSig,ranDom);
        Map<String,Object> map = new HashMap<>();
        map.put("UserID",imUserId);
        String s = restTemplateUtil.postMapData(url, map);
        CommonResultVo result = JSONObject.parseObject(s, CommonResultVo.class);
        if("OK".equals(result.getActionStatus())){
            //自动加群
            //获取群
            String groupId;
            ImGroup imGroup = imGroupService.getGroupOneNotFull();
            if(ObjectUtil.isNull(imGroup)){
                //没有获取到群，则自动创建群
                groupId = imGroupService.createGroup();
            }else {
                groupId = imGroup.getGroupId();
            }
            if(StrUtil.isNotBlank(groupId)){
                imGroupService.addGroupMember(imUserId,groupId);
            }else {
                log.error("创建群失败，不能获取群groupId");
                //创建群失败，不能获取群groupId
            }

            return true;
        }else {
            log.error("注册失败"+result.getErrorInfo());
            return false;
        }
    }


}
